using System;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using DailyReport.Core.Bussines;
using DailyReport.Core.Bussines.IManagers;
using DailyReport.Core.Data.Model;
using log4net;
using Nullables;

public partial class DailyPage : Page
{
    private IDailyManager manager;
    static ILog log = LogManager.GetLogger("DailyPage");
    public string ExecuteJavaScript;
    int userId;

    DateFormatProvider provider;
    
    protected void btnSaveRegister_Click(object sender, EventArgs e)
    {
        
    }
    private string GetCounter(TimeSpan timeSpan)
    {
        StringBuilder builder = new StringBuilder();
        if (timeSpan.Hours < 10)
            builder.Append("0");
        builder.Append(timeSpan.Hours).Append(":");

        if (timeSpan.Minutes < 10)
            builder.Append("0");
        builder.Append(timeSpan.Minutes).Append(":");
        if (timeSpan.Seconds < 10)
            builder.Append("0");
        builder.Append(timeSpan.Seconds);
        return builder.ToString();
    }

    private void SetStartDailyValues(DateTime StartDailyTime)
    {
        MultiView.SetActiveView(View1);
        btnStartDaily.Enabled = false;
        btnEndDaily.Enabled = true;
        StartDaily.Text = string.Format("{0:T} [{0:D}]", StartDailyTime);
        TimeSpan timeSpan = DateTime.Now.Subtract(StartDailyTime);
        DailyCounter.Text = GetCounter(timeSpan);
        DailyCounterValue.Value = "";
        ExecuteJavaScript = "startTimer('" + DailyCounter.ClientID + "');";
        btnEndDaily.Attributes.Add("onclick", "stopTheCounter()");
        EndDaily.Text = string.Empty;
    }
    
    protected void Daily_Command(object sender, CommandEventArgs e)
    {
        //int userId = (int) Session["UserId"];
        if ("start" == e.CommandArgument)
        {
            manager.StartDaily(userId);
            SetStartDailyValues(DateTime.Now);
            /*btnStartDaily.Enabled = false;
            btnEndDaily.Enabled = true;
            StartDaily.Text = string.Format("{0:T} [{0:D}]", DateTime.Now);
            DailyCounter.Text = "00:00:00";
            DailyCounterValue.Value = "";
            ExecuteJavaScript = "startTimer('" + DailyCounter.ClientID + "');";
            btnEndDaily.Attributes.Add("onclick", "stopTheCounter()");
            EndDaily.Text = string.Empty;*/
        }
        else if ("end" == e.CommandArgument)
        {
            log.Debug("End...");
            manager.EndDaily(userId);
            log.Debug("After manager....");
            btnStartDaily.Enabled = true;
            btnEndDaily.Enabled = false;
            EndDaily.Text = string.Format("{0:T} [{0:D}]", DateTime.Now);
            DailyCounter.Text = DailyCounterValue.Value;
            ExecuteJavaScript = string.Empty;
        }
    }

    protected void btnAddRegister_Click(object sender, EventArgs e)
    {
        MultiView.SetActiveView(View2);
    }

    protected void btnSaveNewRegister_Click(object sender, EventArgs e)
    {
        log.Debug("Creating TimeRegister..:" + RegisterName.Text);
        TimeRegister register = new TimeRegister();
        register.Note = RegisterName.Text;
        register.StartTime = DateTime.Now;
        register.Type = int.Parse(RegisterType.SelectedValue);
        

        manager.CreateTimeRegister(register, userId);
        DailyGrid.DataBind();
    }

    
    protected void Page_Load(object sender, EventArgs e)
    {
     log.Debug("Begin load");   
        manager = new DailyManager();
        Session["userId"] = 2;
        RegisterType.DataSource = ConstantsManager.GetInstance().TimeRegisterTypes;
        RegisterType.DataValueField = "Key";
        RegisterType.DataTextField = "Value";
        RegisterType.DataBind();
        userId = (int)Session["userId"];
        Daily currentDaily = manager.GetDailyByUser(userId);
        
        if(currentDaily!=null)
        {
            SetStartDailyValues(currentDaily.StartTime);
            DailyGrid.DataBind();
        }
        
        provider = new DateFormatProvider();
        
        
        StartTime.Text = string.Format("{0:t}", DateTime.Now);
        timer.InnerText = "01:45";

        log.Debug("End load");   
    }


    protected override void OnInitComplete(EventArgs e)
    {
        base.OnInitComplete(e);
        log.Debug("End OnInitComplete");   
    }
}

class DateFormatProvider : ICustomFormatter, IFormatProvider
{
    static ILog log = LogManager.GetLogger("DateFormatProvider");
    public object GetFormat(Type formatType)
    {
        //log.Debug("FormTypoe:" + formatType);
        return this;
        /*
        if (formatType == typeof(ICustomFormatter))
            return this;
        else
            return null;
                     * */
    }

    public string Format(string format, object arg, IFormatProvider formatProvider)
    {
        log.Debug("Form:" + format );
        log.Debug(" - Arg:" + arg.GetType());
        log.Debug(arg == null);
        Nullables.NullableDateTime date = (NullableDateTime)arg;
        if (date.HasValue)
        {
            log.Debug(date);
            log.Debug(date.Value);
            DateTime myDate = date.Value;
            return string.Format(format, date.Value);
        }
        else
            return string.Empty;
    }
}